#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ココ！ MAP - 地図情報登録アプリ　それココだよ - 
#
# index.py

import sys
import os
import re
import cgi
import logging
import wsgiref.handlers

from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import template
from google.appengine.api import users, datastore_types, mail

from datamodel import Entry, Tag

_DEBUG = False

template.register_template_library('templatefilters')

__author__ = 'kyoshida'
__version__ = '0.1'
APP_TITLE = u'ココ! MAP'
APP_DESCRIPTION = u'地図情報登録アプリ それココだよ'
APP_DESCRIPTION_LONG = u'地図情報を登録して、知り合いと共有出来るウェブサービス。'
#APP_URL = 'http://localhost:8080/'
APP_URL = 'http://kokomap.appspot.com/'
NO_USERNAME = 'anonymouse'
    
def get_tag(text):
    """ Get tag from strings """
    
    p = re.compile(r'\[(.+)\](.*)')
    m = p.match(text)
    if m:
        return [m.group(1).split(']['), m.group(2)]
    else:
        return [[], text]
        
def get_auth_url():
    """ Create auth page link text """
    
    user = users.get_current_user()
    if user:
        admin_page = ''
        if users.is_current_user_admin():
            admin_page = '<a href="http://appengine.google.com/dashboard?app_id=kokomap">管理ページ</a> |'
        url = '%s | %s <a href="%s">ログアウト</a>' \
            % (user.nickname(), admin_page, 
               users.create_logout_url("/"))
    else:
        url = '<a href="%s">ログイン</a>' \
            % users.create_login_url("/")
    return url
    
class AppInfo(object):
    """ Application information """
    
    def __init__(self):
        self.title = APP_TITLE
        self.description = APP_DESCRIPTION
        self.description_long = APP_DESCRIPTION_LONG
        self.author = __author__
        self.url = APP_URL
        self.auth_url = get_auth_url()
            

class MailContents(object):
    """ Share mail page information """
    
    def __init__(self, title):
        self.mail_title = u"「%s」の場所をお知らせします" % title
        self.mail_footer = u"※このメールにお心当たりのない場合にはお手数ですが、このメールを削除してください。\n\n" \
                           u"--\n" \
                           u"%(title)s - %(description)s\n" \
                           u"%(url)s" % {'title': APP_TITLE, 'description': APP_DESCRIPTION, 'url': APP_URL}
        
        
class AddHandler(webapp.RequestHandler):
    """ Map info add add handler """
    
    def get(self):
    
        try:           
            template_values = {
                'app' : AppInfo(),
            }

            path = os.path.join(os.path.dirname(__file__),
                'add.html')
            self.response.out.write(template.render(path,
                template_values, debug=_DEBUG))
        except db.BadKeyError:
            self.redirect('/')

    def post(self):
        logging.debug(self.request)
        entry = Entry()

        tags, title = get_tag(self.request.get('title'))
        entry.title = title
        entry.lon = self.request.get('lon')
        entry.lat = self.request.get('lat')
        entry.memo = self.request.get('memo')
        entry.published = self.request.get('published') == 'on'
        
        user = users.get_current_user()
        entry.author = user.nickname() if user else NO_USERNAME
        
        entry.put()
                

class EditHandler(webapp.RequestHandler):
    """ Edit map info handler """

    def get(self, key):
    
        try:
            result = db.get(key)            
            template_values = {
                'app' : AppInfo(),
                'result' : result,
            }

            path = os.path.join(os.path.dirname(__file__), 'edit.html')
            self.response.out.write(template.render(path, template_values,
                debug=_DEBUG))
        except db.BadKeyError:
            self.redirect('/')
            
            
class SendHandler(webapp.RequestHandler):
    """ Send map info handler """

    def get(self, key):
    
        try:
            result = db.get(key)            
            template_values = {
                'app' : AppInfo(),
                'mail' : MailContents(result.title),
                'result' : result,
            }

            path = os.path.join(os.path.dirname(__file__), 'send.html')
            self.response.out.write(template.render(path, template_values,
                debug=_DEBUG))
        except db.BadKeyError:
            self.redirect('/')
            
    def post(self, key):
        logging.debug(self.request.get('title'))
        
        #key = self.request.get('key')
        title = self.request.get('title').encode('utf-8')
        to_address = self.request.get('to_address')
        from_address = self.request.get('from_address')
        body = self.request.get('body').encode('utf-8')
        
        logging.debug(key)
        logging.debug(to_address)
        logging.debug(from_address)
        logging.debug(body)
        
        mail.send_mail(from_address, to_address, title, body)
            
            
class KeyHandler(webapp.RequestHandler):
    """ Map page handler """

    def get(self, key):
    
        try:
            result = db.get(key)
            template_values = {
                'app' : AppInfo(),
                'result' : result,
            }

            path = os.path.join(os.path.dirname(__file__),
                'key.html')
            self.response.out.write(template.render(path,
                template_values, debug=_DEBUG))
        except db.BadKeyError:
            self.redirect('/')


class UpdateHandler(webapp.RequestHandler):
    """ Update map info handler """

    def post(self):
        logging.debug(self.request.get('title'))
        
        key = self.request.get('key')
        result = db.get(key)
        tags, result.title = get_tag(self.request.get('title'))
        result.lon = self.request.get('lon')
        result.lat = self.request.get('lat')
        result.memo = self.request.get('memo')
        result.published = self.request.get('published') == 'on'
            
        result.put()

        self.redirect('/key/' + key)
        
        
class HelpHandler(webapp.RequestHandler):
    """ Help page handler """
    
    def get(self):
        template_values = {
            'app' : AppInfo(),
            'simple_login_url' : users.create_login_url("/"),
        }

        path = os.path.join(os.path.dirname(__file__),
            'help.html')
        self.response.out.write(template.render(path,
            template_values, debug=_DEBUG))
        
        
class DelHandler(webapp.RequestHandler):
    """ Map data delete handler """

    def get(self, key):
        logging.debug(self.request)
        
        try:
            result = db.get(key)
            db.delete(result)
        except db.BadKeyError:
            pass
            
        self.redirect('/')
        
        
class RssHandler(webapp.RequestHandler):
    """ RSS feed handler """

    def get(self):
        results = Entry.all()
        results.filter('published =', True)

        template_values = {
            'app' : AppInfo(),
            'results' : results,
        }

        path = os.path.join(os.path.dirname(__file__),
            'rss.html')
        self.response.out.write(template.render(path,
            template_values, debug=_DEBUG))
            

class SitemapHandler(webapp.RequestHandler):
    """ Sitemap page handler """

    def get(self):
        results = Entry.all()
        results.filter('published =', True)

        template_values = {
            'app' : AppInfo(),
            'results' : results,
        }

        path = os.path.join(os.path.dirname(__file__),
            'sitemap.xml')
        self.response.out.write(template.render(path,
            template_values, debug=_DEBUG))


class RootHandler(webapp.RequestHandler):
    """ Root page handler """

    def get(self):
    
        published_results = Entry.all()
        published_results.filter('published =', True)
        
        private_results = None
        user = users.get_current_user()
        if user:
            private_results = Entry.all()
            private_results.filter('author =', user.nickname())
            private_results.filter('published =', False)
            
                
        template_values = {
            'app' : AppInfo(),
            'published_results' : published_results,
            'private_results' : private_results,
        }

        path = os.path.join(os.path.dirname(__file__),
            'index.html')
        self.response.out.write(template.render(path, 
            template_values, debug=_DEBUG))


def main():
    application = webapp.WSGIApplication(
        [
            ('/add', AddHandler),
            ('/edit/(.*)', EditHandler),
            ('/send/(.*)', SendHandler),
            ('/key/(.*)', KeyHandler),
            ('/update', UpdateHandler),
            ('/help', HelpHandler),
            ('/del/(.*)', DelHandler),
            ('/rss', RssHandler),
            ('/sitemap.xml', SitemapHandler),
            ('/', RootHandler),
        ], debug=_DEBUG)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()